package mysqllib

import (
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"log"
	"time"
)

var (
	Db *gorm.DB
)

// NewClient 初始化 Mysql
func InitDB() {
	dns := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		viper.GetString("database.username"),
		viper.GetString("database.password"),
		viper.GetString("database.host"),
		viper.GetString("database.port"),
		viper.GetString("database.dbname"),
	)
	fmt.Println(dns)
	var err error
	Db, err = gorm.Open(mysql.Open(dns), &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true, //关闭外键
		NamingStrategy: schema.NamingStrategy{
			SingularTable: false, //默认在表的后面加s
		},
	})
	if err != nil {
		log.Println("数据库连接失败,err:", err)
		panic(err)
	}
	sqlDb, _ := Db.DB()
	sqlDb.SetMaxIdleConns(50)                   // 连接池中的最大闲置连接数
	sqlDb.SetMaxOpenConns(100)                  // 数据库的最大连接数量
	sqlDb.SetConnMaxLifetime(100 * time.Second) // 连接的最大可复用时间
}
